package com.java.second_goods.controller;

import com.java.second_goods.common.AjaxResult;
import com.java.second_goods.entity.Goods;
import com.java.second_goods.entity.GoodsImage;
import com.java.second_goods.service.IGoodsImageService;
import com.java.second_goods.service.IGoodsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品信息
 */
@RestController
@RequestMapping("/api/goods")
@Tag(name = "商品管理", description = "商品相关接口")
public class GoodsController extends BaseController {

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IGoodsImageService goodsImageService;

    /**
     * 获取商品列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取商品列表", description = "获取商品列表")
    public AjaxResult list(Goods goods) {
        startPage(1,10);
        List<Goods> list = goodsService.selectGoodsList(goods);
        return getDataTable(list);
    }

    /**
     * 获取热门商品列表
     */
    @GetMapping("/popular")
    @Operation(summary = "获取热门商品", description = "获取热门商品列表")
    public AjaxResult popular(@RequestParam(defaultValue = "10") Integer limit) {
        List<Goods> list = goodsService.selectPopularGoods(limit);
        return success(list);
    }

    /**
     * 获取新品列表
     */
    @GetMapping("/new")
    @Operation(summary = "获取新品列表", description = "获取新品列表")
    public AjaxResult newGoods(@RequestParam(defaultValue = "10") Integer limit) {
        List<Goods> list = goodsService.selectNewGoods(limit);
        return success(list);
    }

    /**
     * 获取用户发布的商品列表
     */
    @GetMapping("/seller/{sellerId}")
    @Operation(summary = "获取卖家商品", description = "获取用户发布的商品列表")
    public AjaxResult sellerGoods(@PathVariable("sellerId") Integer sellerId) {
        List<Goods> list = goodsService.selectGoodsBySellerId(sellerId);
        return success(list);
    }

    /**
     * 获取商品详细信息
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取商品详情", description = "根据商品ID获取商品详细信息")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        // 增加浏览次数
        goodsService.increaseViewCount(id);

        Goods goods = goodsService.selectGoodsById(id);
        List<GoodsImage> images = goodsImageService.selectImagesByGoodsId(id);

        Map<String, Object> data = new HashMap<>();
        data.put("goods", goods);
        data.put("images", images);

        return success(data);
    }

    /**
     * 新增商品
     */
    @PostMapping
    @Operation(summary = "新增商品", description = "新增商品")
    public AjaxResult add(@RequestBody Goods goods) {
        int rows = goodsService.insertGoods(goods);
        AjaxResult ajax = toAjax(rows);
        if (rows > 0) {
            ajax.put("goodsId", goods.getId());
        }
        return ajax;
    }

    /**
     * 修改商品
     */
    @PutMapping
    @Operation(summary = "修改商品", description = "修改商品")
    public AjaxResult edit(@RequestBody Goods goods) {
        return toAjax(goodsService.updateGoods(goods));
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/{ids}")
    @Operation(summary = "删除商品", description = "删除商品")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(goodsService.deleteGoodsByIds(ids));
    }

    /**
     * 上传商品图片
     */
    @PostMapping("/upload/{goodsId}")
    @Operation(summary = "上传商品图片", description = "上传商品图片")
    public AjaxResult upload(@PathVariable("goodsId") Integer goodsId,
                             @RequestParam("files") MultipartFile[] files) {
        // 这里应该有文件上传的逻辑，上传到服务器或云存储
        // 为简化，这里只模拟处理
        List<GoodsImage> images = goodsImageService.selectImagesByGoodsId(goodsId);
        boolean hasMainImage = false;
        if (images != null && !images.isEmpty()) {
            for (GoodsImage image : images) {
                if (image.getIsMain() == 1) {
                    hasMainImage = true;
                    break;
                }
            }
        }

        // 处理上传的图片
        for (int i = 0; i < files.length; i++) {
            GoodsImage goodsImage = new GoodsImage();
            goodsImage.setGoodsId(goodsId);
            goodsImage.setImageUrl("/upload/goods/" + System.currentTimeMillis() + "_" + files[i].getOriginalFilename());
            goodsImage.setSortOrder(images.size() + i);
            // 如果还没有主图，则设置第一张为主图
            goodsImage.setIsMain(!hasMainImage && i == 0 ? 1 : 0);
            goodsImage.setStatus(1);
            goodsImageService.insertGoodsImage(goodsImage);

            // 如果是第一张图片且是主图，更新商品的主图字段
            if (!hasMainImage && i == 0) {
                Goods goods = new Goods();
                goods.setId(goodsId);
                goods.setImage(goodsImage.getImageUrl());
                goodsService.updateGoods(goods);
            }
        }

        return success();
    }

    /**
     * 商品上架
     */
    @PutMapping("/publish/{id}")
    @Operation(summary = "商品上架", description = "上架商品")
    public AjaxResult publish(@PathVariable("id") Integer id) {
        return toAjax(goodsService.publishGoods(id));
    }

    /**
     * 商品下架
     */
    @PutMapping("/unpublish/{id}")
    @Operation(summary = "商品下架", description = "下架商品")
    public AjaxResult unpublish(@PathVariable("id") Integer id) {
        return toAjax(goodsService.unpublishGoods(id));
    }

    /**
     * 增加收藏次数
     */
    @PutMapping("/favorite/add/{id}")
    @Operation(summary = "增加收藏次数", description = "增加商品收藏次数")
    public AjaxResult addFavorite(@PathVariable("id") Integer id) {
        return toAjax(goodsService.increaseFavoriteCount(id));
    }

    /**
     * 减少收藏次数
     */
    @PutMapping("/favorite/cancel/{id}")
    @Operation(summary = "减少收藏次数", description = "减少商品收藏次数")
    public AjaxResult cancelFavorite(@PathVariable("id") Integer id) {
        return toAjax(goodsService.decreaseFavoriteCount(id));
    }

    /**
     * 按分类统计商品数量
     */
    @GetMapping("/stats/category")
    @Operation(summary = "分类统计", description = "按分类统计商品数量")
    public AjaxResult categoryStats() {
        return success(goodsService.countGoodsByCategory());
    }
}